#!/usr/bin/perl
#
# Fix up charsets of a record (any record)
#
use Counter;
use Counter::CGI;
use CounterCGI;
use PHP::Session;
use Encode;

my $q = Counter::CGI->new;
my $sessid = $q->cookie("PHPSESSID");
# note - corrupted session file will cause the stuff to bomb at this point. Bad.
my $session = PHP::Session->new($sessid, { create => 1 });

$file = $q->param("file");
$f_key = $q->param("f_key");
$counter = Counter::open(O_RDWR);
$cfile = Counter::openfile($file);
$rec = $cfile->get($f_key);
if (!$rec) {
   returnwithmessage("No such record");
}
   
if ($q->param("show")) {
} elsif ($q->param("to-utf8")) {
    eval {
	my $oldtext = Encode::encode("utf-8", $rec->textform(), Encode::FB_CROAK);
	my $newtext = Encode::decode("iso-8859-1", $oldtext, Encode::FB_CROAK);
	$rec = $cfile->makeobject($f_key, $newtext);
	$rec->store();
    };
    if ($@) {
	returnwithmessage("Error in conversion: $@");
    }
} elsif ($q->param("from-utf8")) {
    eval {
	my $oldtext = Encode::encode("iso-8859-1", $rec->textform(), Encode::FB_CROAK);
	my $newtext = Encode::decode("utf-8", $oldtext, Encode::FB_CROAK);
	$rec = $cfile->makeobject($f_key, $newtext);
	$rec->store();
    };
    if ($@) {
	returnwithmessage("Error in conversion: $@");
    }
} else {
  returnwithmessage("No recognizable command");
}   
# Not set - charset confusion breaks session files.
# $session->set("cmd_recval" => $rec->textform());
$session->set("cmd_file" => $file);
$session->set("cmd_f_key" => $f_key);
returnwithmessage("Finished");

sub returnwithmessage {
    my $message = shift;
    $session->set("message" => $message);
    $returnurl = $session->get("showpage");
    #warn "Returning to $returnurl\n";
    $session->save();
    print $q->redirect($returnurl);
    print <<EoF;
<html><head>
<title>You should have been redirected</title>
</head><body>
You should not have seen this. You should have been at
<a href="$returnurl">$returnurl</a>.
<p>
Please report the bug to webmaster&#x40;counter.li.org.
</body>
</html>
EoF
    exit(0);
}
